package Reference;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * @Author: dch
 * @Date: 2020/5/18 13:56
 * @Description:
 */
public class ReferenceQueueDemo {
    public static void main(String[] args) throws InterruptedException {

        Object obj = new Object();
        //定义引用队列
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue();
        //定义弱引用
        WeakReference<Object> weakReference = new WeakReference<Object>(obj,referenceQueue);

        //gc回收前
        System.out.println(obj);
        //获取弱引用对象
        System.out.println(weakReference.get());
        //引用队列进行消费
        System.out.println(referenceQueue.poll());

        System.out.println("===================");
        obj = null;
        System.gc();
        Thread.sleep(500);

        //gc回收后
        System.out.println(obj);
        //获取弱引用对象
        System.out.println(weakReference.get());
        //引用队列进行消费
        System.out.println(referenceQueue.poll());
    }
}
